import java.util.concurrent.locks.ReentrantLock;

/**
 * <p>
 * </p>
 *
 * @author zhuolin
 * @since 2020/5/29
 */
public class TryLock implements Runnable {

    public static ReentrantLock lock1 = new ReentrantLock();

    public static ReentrantLock lock2 = new ReentrantLock();

    public TryLock(int lock) {
        this.lock = lock;
    }

    int lock;

    @Override
    public void run() {
        if (lock == 1) {
            while (true) {
                if (lock1.tryLock()) {
                    try {
                        System.out.println(Thread.currentThread().getName() + ":lock1");
                        try {
                            Thread.sleep(500);
                            if (lock2.tryLock()) {
                                try {
                                    System.out.println(Thread.currentThread().getName() + ":lock2");
                                    System.out.println(Thread.currentThread().getName() + ":running");
                                    return;
                                } finally {
                                    lock2.unlock();
                                }
                            }
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    } finally {
                        lock1.unlock();
                    }
                }
            }
        } else {
            while (true) {
                if (lock2.tryLock()) {
                    try {
                        System.out.println(Thread.currentThread().getName() + ":lock2");
                        try {
                            Thread.sleep(500);

                            if (lock1.tryLock()) {
                                try {
                                    System.out.println(Thread.currentThread().getName() + ":lock1");
                                    System.out.println(Thread.currentThread().getName() + ":running");
                                    return;
                                } finally {
                                    lock1.unlock();
                                }
                            }
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    } finally {
                        lock2.unlock();
                    }
                }
            }
        }
    }


    public static void main(String[] args) throws InterruptedException {
        TryLock tryLock1 = new TryLock(1);
        TryLock tryLock2 = new TryLock(2);
        Thread t1 = new Thread(tryLock1);
        Thread t2 = new Thread(tryLock2);
        t1.start();
        t2.start();
    }
}
